package com.haighcom.controller;

import com.haighcom.common.QiniuUtils;
import com.haighcom.common.RedisConstant;
import com.haighcom.config.RedisConfig;
import com.haighcom.constant.MessageConstant;
import com.haighcom.entity.PageResult;
import com.haighcom.entity.QueryPageBean;
import com.haighcom.entity.Result;
import com.haighcom.model.TSetmeal;
import com.haighcom.service.OrderSettingService;
import com.haighcom.service.SetmealService;
import org.apache.tomcat.Jar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    private static JedisPool jedisPool;
    @Autowired
    private RedisConfig redisConfig;

    @PostConstruct
    public void init(){
        jedisPool = redisConfig.redisPoolFactory();
    }

    @Autowired
    private SetmealService setmealService;

    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile){
        String originalFilename = imgFile.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String ex = originalFilename.substring(index-1);

        String fileName = UUID.randomUUID().toString()+ex;

        try {
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
        return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
    }
    @RequestMapping("/add")
    public Result add(@RequestBody TSetmeal tSetmeal,Integer[] checkgroupIds){
        try {
            setmealService.add(tSetmeal,checkgroupIds);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
    }
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult =setmealService.pageQuery(queryPageBean);
        return pageResult;
    }


}
